package atguigu.atomic;
import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceDemo {
	
    static AtomicStampedReference<String> asr = new AtomicStampedReference("介绍的女朋友", 0);

    public static void main(String[] args) throws InterruptedException {
    	
        final String oldReference = asr.getReference();//初始值，表示介绍的女朋友
        
        final int oldStamp = asr.getStamp();//初始版本0，表示介绍的女朋友没有离过婚

        Thread thread1 = new Thread(() -> {
            String newReference = oldReference + " 离婚1次";
            boolean first = asr.compareAndSet(oldReference, newReference,oldStamp, oldStamp + 1);
            if (first) {
                System.out.println("介绍的女朋友第一次离婚。。。");
            }

            boolean second = asr.compareAndSet(newReference, oldReference + "又离婚了",oldStamp + 1, oldStamp + 2);
            if (second) {
                System.out.println("介绍的女朋友第二次离婚。。。");
            }
        }, "介绍的女朋友离婚");

        Thread thread2 = new Thread(() -> {
            String reference = asr.getReference();//介绍的女朋友最新状态

            //判断介绍的女朋友最新状态是否符合老王的要求
            boolean flag = asr.compareAndSet(reference, reference + "没有离过婚",
                    oldStamp, oldStamp + 1);
            if (flag) {
                System.out.println("老王笑嘻嘻地对我说，介绍的女朋友符合我的要求");
            } else {
                System.out.println("老王拳头紧握地对我说，介绍的女朋友居然离过" + asr.getStamp() + "次婚,不符合我要求！！！！");
            }
        }, "老王相亲");
        
        thread1.start();
        thread1.join();
        thread2.start();
        thread2.join();
    }
}